<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import {
    ref,
    reactive,
    shallowRef,
    onMounted,
    watch,
    onBeforeUnmount,
    inject,
} from "vue";

const axios = inject("axios");

const key = "c350c3dd9395902313f1c247a04e8c01";
const securityJsCode = "71f7722071b828eef6b23e84bd4286a9";

//!这里的安全密钥不写会导致 行政区查询等API无法使用
window._AMapSecurityConfig = { securityJsCode };

// 颜色组
const COLOR_MAIN = "rgba(0,0,205, 0.5)";
const COLOR_HIGHLIGHT = "rgba(50, 50, 255, 0.5)";
const COLOR_SELECT = "rgba(0,255,127, 0.5)";
const COLOR_SELECT_HIGHLIGHT = "rgba(0,255,200, 0.5)";
const COLOR_NULL = "rgba(0, 0, 0, 0)";
const COLOR_PROVINCE_STROKE = "rgba(105,105,105,1)";
const COLOR_CITY_STROKE = "rgba(105,105,105,0.2)";

var map = shallowRef(null); // 这里一定使用非深度监听 否则会出问题
var province = [
    "520000",
    "540000",
    "530000",
    "500000",
    "360000",
    "340000",
    "510000",
    "350000",
    "430000",
    "420000",
    "410000",
    "330000",
    "640000",
    "650000",
    "440000",
    "370000",
    "450000",
    "630000",
    "320000",
    "140000",
    "460000",
    "310000",
    "110000",
    "130000",
    "230000",
    "220000",
    "210000",
    "150000",
    "120000",
    "620000",
    "610000",
    "710000",
    "810000",
    "820000",
];
var dis_province = {
    getDistrictByContainerPos: () => {},
};

var move_flag = 1;
function initMap() {
    AMapLoader.load({
        key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [""], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                //设置地图容器id
                viewMode: "3D", //是否为3D地图模式
                zoom: 4.5,
                zooms: [4, 7], //初始化地图级别
                center: [105.602725, 37.076636], //初始化地图中心点位置
            });

            map.setMapStyle("amap://styles/dark"); // 地图样式

            dis_province = new AMap.DistrictLayer.Province({
                zIndex: 12,
                adcode: province,
                depth: 1,
                styles: {
                    fill: function (props) {
                        return COLOR_MAIN;
                    },
                    "province-stroke": COLOR_PROVINCE_STROKE,
                    "city-stroke": COLOR_CITY_STROKE, //中国地级市边界
                    "stroke-width": 1,
                },
            });
            var layers = [dis_province]; // 添加图层
            map.add(layers);

            // 加载完成时
            map.on("complete", () => {
                // var map = new AMap.Map("container", {
                //     zoom: 10, //设置地图的缩放级别
                // });
                setTimeout(() => {
                    setStyleByProvince(2);
                }, 2000)
            // map.setFitView();
            });

            map.on("mousemove", function (ev) {
                var px = ev.pixel; // 拾取所在位置的行政区
                var props = dis_province.getDistrictByContainerPos(px);

                if (props) {
                    let adcode = props.adcode;
                    if (adcode) {
                        setStyleByProvince(1, adcode);
                    }
                }
            });

            map.on("click", function (ev) {
                var px = ev.pixel; // 拾取所在位置的行政区
                var props = dis_province.getDistrictByContainerPos(px);
                if (props) {
                    var adcode = props.adcode;
                    if (adcode) {
                        select_city_adcode = adcode;
                        setStyleByProvince(1, adcode);
                        adcodeToCity(adcode + "").then((res) => {
                            messageBox(`已选择${res[1]}`, 1);
                        });
                    }
                } else {
                    select_city_adcode = 0;
                    setStyleByProvince(0, adcode);
                    real_city_name.value = "";
                }
            });

            map.on("moveend", () => {
                move_flag = 0;
                console.log("00");
            });

            map.on("movestart", () => {
                move_flag = 1;
                console.log("11");
            });
        })
        .catch((e) => {
            console.log(e);
        });
}

// 向后端请求城市数据
var city_item;
var colors = {};  // 设置省区颜色
async function getCityItem() {
    let res = await axios.get("api/login");
    city_item = res.data.rows;
    // console.log(city_item);
    for (let i = 0; i < city_item.length; i++) {
        let tmp_color = Math.round(Math.random() * 100);
        city_item[i].main_index = tmp_color
        colors[city_item[i].adcode] = "rgba(" + tmp_color + ",0,205, 0.5)";
    }
}
// 获取颜色
function getColorByAdcode(adcode) {
    return colors[adcode];
}

// 设置城市样式
var select_city_adcode;
function setStyleByProvince(model, adcode) {
    switch (model) {
        case 0: {
            dis_province.setStyles({
                fill: (props) => {
                    return getColorByAdcode(props.adcode);
                },
                "province-stroke": COLOR_PROVINCE_STROKE,
                "city-stroke": COLOR_CITY_STROKE, //中国地级市边界
                "stroke-width": 1,
            });
            break;
        }
        case 1: {
            dis_province.setStyles({
                fill: (props) => {
                    if (props.adcode == adcode) {
                        if (props.adcode == select_city_adcode) {
                            return COLOR_SELECT_HIGHLIGHT;
                        } else {
                            return COLOR_HIGHLIGHT;
                        }
                    } else if (props.adcode == select_city_adcode) {
                        return COLOR_SELECT;
                    } else {
                        return getColorByAdcode(props.adcode);
                    }
                },
                "province-stroke": COLOR_PROVINCE_STROKE,
                "city-stroke": COLOR_CITY_STROKE, //中国地级市边界
                "stroke-width": 1,
            });
            break;
        }
        case 2: {
            dis_province.setStyles({
                fill: (props) => {
                    return getColorByAdcode(props.adcode);
                },
                "province-stroke": COLOR_PROVINCE_STROKE,
                "city-stroke": COLOR_CITY_STROKE, //中国地级市边界
                "stroke-width": 1,
            });
            break;
        }
        default: {
            throw "请输入正确的模式参数";
        }
    }
}

//根据cityname、adcode、citycode设置地图位置
const city_name = ref("");
const gotoCity = () => {
    var val = city_name.value;
    if (!val) {
        val = "北京市";
    }
    adcodeToCity(val)
        .then((res) => {
            map.setCity(res[1]);
            messageBox(`已跳转至${res[1]}`);
        })
        .catch((error) => {
            if (error == 1) {
                messageBox("请输入完整的城市名称");
            } else {
                messageBox("请输入正确的城市名称");
            }
        });
};

// 根据城市名或adcode查询adcode和城市名
const real_city_name = ref("");
function adcodeToCity(val) {
    return new Promise((resolve, reject) => {
        AMap.plugin("AMap.DistrictSearch", function () {
            var districtSearch = new AMap.DistrictSearch({
                // 关键字对应的行政区级别，country表示国家
                level: "city",
                //  显示下级行政区级数，1表示返回下一级行政区
                // subdistrict: 0,
            });

            // 搜索所有省/直辖市信息
            districtSearch.search(val, function (status, result) {
                // 查询成功时，result即为对应的行政区信息
                if (status != "no_data") {
                    if (result.districtList.length == 1) {
                        var adcode = result.districtList[0].adcode;
                        select_city_adcode = adcode;
                        setStyleByProvince(1, adcode);
                        real_city_name.value = result.districtList[0].name;

                        console.log(result.districtList[0].adcode,
                            result.districtList[0].name,);

                        resolve([
                            result.districtList[0].adcode,
                            result.districtList[0].name,
                        ]);
                    } else {
                        reject("1");
                    }
                } else {
                    reject("2");
                }
            });
        });
    });
}

// 信息窗口
var message_item_count = 0;
const message_item = ref("");
function messageBox(msg, time = 2) {
    message_item.value = msg;
    if (message_item_count < 3) {
        message_item_count = message_item_count + time;
    }
}
// 信息窗口辅助函数
function messageBoxCount() {
    if (message_item_count > 0) {
        message_item_count = message_item_count - 1;
    } else {
        message_item.value = "";
    }
}
var t1 = window.setInterval(messageBoxCount, 1000);

onMounted(() => {
    initMap();
    getCityItem();
});

onBeforeUnmount(() => {
    map.destroy();
    window.clearInterval(t1);
});
</script>

<template>
    <div id="container"></div>

    <div class="input-card location">
        <h4>设置地图当前行政区</h4>
        <div class="input-item">
            <input
                id="city-name"
                placeholder="XX市"
                type="text"
                style="margin-right: 1rem"
                v-model="city_name"
            /><button class="btn" id="query" @click="gotoCity">
                去指定城市
            </button>
        </div>
    </div>
    <div class="input-card information">
        <h4>当前所选政区信息</h4>
        <div class="input-item">
            <p>{{ real_city_name }}</p>
            <p>各种信息.. 图表..</p>
        </div>
        <div></div>
    </div>
    <div class="message-box" v-if="message_item">
        <div>⚠ {{ message_item }}</div>
    </div>
</template>

<style scoped>
#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100%;
    min-height: 100vh;
}

.message-box {
    position: fixed;
    bottom: 90vh;
    width: 100%;
    display: flex;
    justify-content: center;
}

@keyframes message-box {
    0% {
        transform: translateY(-10vh);
    }
}

.message-box div {
    animation-name: message-box;
    animation-duration: 0.2s;
    text-align: center;
    padding: 4px 8px;
    border: 1px solid #ffffff;
    font-weight: 100;
    /* color: #f7e225; */
    color: #ffffff;
    user-select: none;
    /* width: 100px; */
    /* background-color: rgba(39, 204, 47, 0.5); */
    background-color: #25f7f000;
}

.query {
    bottom: 1rem;
    right: 1rem;
}
.location {
    bottom: 1rem;
    right: 1rem;
}

.information {
    bottom: 9rem;
    right: 1rem;
}

.input-card {
    /* display: flex; */
    /* flex-direction: column; */
    /* min-width: 0; */
    /* word-wrap: break-word; */
    background-color: rgba(75, 75, 75, 0.59);
    /* background-clip: border-box; */
    /* border-radius: 0.25rem; */
    width: 22rem;
    /* border-width: 0; */
    /* border-radius: 0.4rem; */
    /* box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5); */

    position: fixed;

    /* bottom: 1rem; */
    /* right: 1rem; */
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    padding: 0.75rem 1.25rem;
}
.input-card h4 {
    margin: 1rem 0rem;
    color: #b9b9b9;
}

select,
input[type="text"],
input[type="date"] {
    display: inline-block;
    /* width: 100%; */
    padding: 0.375rem 1.75rem 0.375rem 0.75rem;
    line-height: 1.5;
    color: #98a1a9;
    vertical-align: middle;
    /* background: #fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center; */
    background-color: #0000008c;
    background-size: 8px 10px;
    border: 1px solid #ced4da;
    /* border-radius: .25rem; */
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

/* input[type=text],input[type=date] {
  background: #fff;
  padding: .375rem .75rem;
} */

select:focus,
input[type="text"]:focus,
input[type="date"]:focus {
    border-color: #80bdff;
    outline: 0;
    box-shadow: 0 0 0 0.1rem rgba(128, 189, 255, 0.1);
}

.btn {
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border: 1px solid transparent;
    /* transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
        border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; */
    background-color: transparent;
    background-image: none;
    color: #25a5f7;
    border-color: #25a5f7;
    padding: 0.25rem 0.5rem;
    line-height: 1.5;
    /* border-radius: 1rem; */
    -webkit-appearance: button;
    cursor: pointer;
}

.btn:hover {
    color: #fff;
    background-color: #25a5f7;
    border-color: #25a5f7;
    text-decoration: none;
}

/* .btn:focus {
  outline: 0;
  box-shadow: none;
} */

/* select:focus::-ms-value, input[type=text]:focus::-ms-value,input[type=date]:focus::-ms-value {
  color: #495057;
  background-color: #fff
} */
</style>
